package cn.hdu.liang.concurrency;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

class FibSum {
    private static ExecutorService exec;

    private static int fib(int n) {
        if(n < 2) {
            return 1;
        }
        return fib(n - 1) + fib(n - 2);
    }

    public static synchronized Future<String> runTask(final int n) {
        assert exec != null;
        return exec.submit(() -> {
            StringBuilder sb = new StringBuilder();
            for(int i = 0; i < n; i++) {
                sb.append(fib(i));
            }
            return sb.toString();
        });
    }

    public static synchronized void init() {
        if(exec == null) {
            exec = Executors.newCachedThreadPool();
        }
    }

    public static synchronized void shutdown() {
        if(exec != null) {
            exec.shutdown();
        }
        exec = null;
    }
}

public class Exam10 {
    public static void main(String[] args) {
        List<Future<String>> results = new ArrayList<>();
        FibSum.init();
        for(int i = 0; i < 20; i++) {
            results.add(FibSum.runTask(i));
        }
        Thread.yield();
        FibSum.shutdown();
        for(Future<String> fs : results) {
            try {
                System.out.println(fs.get());
            } catch(Exception e) {
                e.printStackTrace();
            }
        }
    }
}
